﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.IO;
using AnyOffice.DAL;
using AnyOffice.Components;
using System.Data.SqlClient;
namespace AnyOffice.Web
{

    /// <summary>
    /// 文件柜操作常用方法 cth
    /// </summary>
    public class Public_foldGX : BasePage
    {
        public static FileTypeDao BLLftype = new FileTypeDao();
        public static DiskGXDao disk = new DiskGXDao();
        public static DiskTypeGXDao dbll = new DiskTypeGXDao();
        public static int filetypeID = 1;//文件夹
        public static string DiskTypeName = "公共文档柜";
        public static string DiskTypeName2 = "个人文档柜";
        private static SqlConnection conn = new SqlConnection(ConfigManager.ConnectionString);

        /// <summary>
        /// 根据文件后缀得到文件类型ID
        /// </summary>
        public static int GetType(string typename)
        {
            int ftypeid = 44;  //unknown.gif
            if (typename.Length > 0)
            {
                string str = "FileTypeName like'%" + typename + "%' or FileTypeDesc like '%" + typename + "%'";
                DataSet ds = BLLftype.GetList(conn, str);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    ftypeid = Convert.ToInt32(ds.Tables[0].Rows[0]["FileTypeID"]);
                }
                else { ftypeid = GetType("unknown"); }
            }
            return ftypeid;

        }


        /// <summary>
        /// 文件或文件夹重命名
        /// </summary>
        /// <param name="OldName">原名</param>
        /// <param name="NewName">新名</param>
        /// <param name="type">类型（1是文件夹）</param>
        public static bool RemoveFiles(string OldName, string NewName, string type)
        {
            try
            {
                if (type == "1")
                {
                    if (!Directory.Exists(NewName))
                    {
                        Directory.Move(OldName, NewName);
                        return true;
                    }
                }
                else
                {
                    if (!File.Exists(NewName))
                    {
                        File.Move(OldName, NewName);
                        return true;
                    }
                }
                return false;
            }
            catch { return false; }

        }

        /// <summary>
        /// 获得文件柜里文件的物理路径
        /// </summary>
        /// <param name="FolderPathName">相对父节点路径</param>
        /// <param name="filename">文件名</param>
        /// <param name="diskTypeID">网络硬盘类型</param>
        public static string GetPath(string FolderPathName, string filename, string diskTypeID)
        {
            string path = "";
            try
            {
                if (FolderPathName.Length > 0)
                {
                    DiskTypeGXDao dt = new DiskTypeGXDao();
                    AnyOffice.Model.DiskTypeGX mode = dt.GetModel(conn, Convert.ToInt32(diskTypeID));
                    path = mode.BasePath + "\\" + FolderPathName.Replace('/', '\\');
                    if (filename.Length > 0)
                    {
                        path += "\\" + filename;
                    }
                }
            }
            catch (Exception ex) { return ex.Message; }
            return path;
        }


        /// <summary>
        ///  判定用户是否有管理权限
        /// </summary>
        public static bool IsCanDel(string userid, string did)
        {
            AnyOffice.Model.DiskGX d = disk.GetModel(conn, Convert.ToInt32(did));
            string[] arr = d.WriteUser.Split(',');
            if (arr.Contains(userid) || userid == "admin")
            {
                return true;
            }
            return false;
        }


        /// <summary>
        ///  是否有查看权限
        /// </summary>
        public static bool IsCanRed(string userid, string deptid, string roleid, string did)
        {
            AnyOffice.Model.DiskGX d = disk.GetModel(conn, Convert.ToInt64(did));
            string[] arr = d.ReadDept.Split(',');
            if (arr.Contains(deptid) || d.ReadDept == "ALL_DEPT")
            {
                return true;
            }
            arr = d.ReadRole.Split(',');
            if (arr.Contains(roleid))
            {
                return true;
            }
            arr = d.ReadUser.Split(',');
            if (arr.Contains(userid) || userid == "admin")
            {
                return true;
            }
            arr = d.WriteUser.Split(',');
            if (arr.Contains(userid))
            {
                return true;
            }
            if (IsCanDownLoad(userid, deptid, roleid, did))
            {
                return true;
            }

            return false;
        }


        /// <summary>
        ///  是否有下载权限
        /// </summary>
        public static bool IsCanDownLoad(string userid, string deptid, string roleid, string did)
        {
            AnyOffice.Model.DiskGX d = disk.GetModel(conn, Convert.ToInt64(did));
            string[] arr = d.DownloadDept.Split(',');
            if (arr.Contains(deptid) || d.DownloadDept == "ALL_DEPT")
            {
                return true;
            }
            arr = d.DownloadRole.Split(',');
            if (arr.Contains(roleid))
            {
                return true;
            }
            arr = d.DownloadUser.Split(',');
            if (arr.Contains(userid) || userid == "admin")
            {
                return true;
            }
            arr = d.WriteUser.Split(',');
            if (arr.Contains(userid))
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// 文件移动
        /// </summary>
        /// <param name="strid">移动的id</param>
        /// <param name="npath">移动到得路径</param>
        /// <returns></returns>
        public static bool MapPathMove(string strid, string npath)
        {
            bool isSuc = false;
            try
            {
                List<AnyOffice.Model.DiskGX> files = disk.GetModelList(conn, " DiskID in(" + strid + ")");
                foreach (AnyOffice.Model.DiskGX f in files)
                {
                    string oldpath = "";
                    string newpath = "";
                    oldpath = disk.GetParentPath(conn, f.DiskID.ToString(), "");
                    newpath = disk.GetParentPath(conn, npath, "");
                    if (f.FileTypeID == 1)
                    {
                        oldpath = Public_foldGX.GetPath(oldpath, "", f.DiskTypeID.ToString());
                        newpath = Public_foldGX.GetPath(newpath, f.Name, f.DiskTypeID.ToString());
                        if (Directory.Exists(oldpath))
                        {
                            if (Directory.Exists(newpath)) //如果目标目录已存在
                            {
                                isSuc = CopyDir(oldpath, newpath); //判断多层覆盖是否成功
                            }
                            else
                            {
                                Directory.Move(oldpath, newpath);
                            }
                            isSuc = true;
                        }
                        else { isSuc = false; }
                    }
                    else
                    {   //文件覆盖
                        oldpath = Public_foldGX.GetPath(oldpath, "", f.DiskTypeID.ToString());
                        newpath = Public_foldGX.GetPath(newpath, f.Name, f.DiskTypeID.ToString());
                        FileInfo fi = new FileInfo(oldpath);
                        File.Copy(oldpath, newpath, true);
                        File.Delete(oldpath);
                        isSuc = true;
                    }
                }

                isSuc = true;
            }
            catch
            {
                return false;
            }
            return isSuc;
        }


        /// <summary>
        /// 文件夹覆盖
        /// </summary>
        /// <param name="srcPath">原目录</param>
        /// <param name="aimPath">移动目标目录</param>
        public static bool CopyDir(string srcPath, string aimPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                {
                    aimPath += Path.DirectorySeparatorChar;
                }
                // 判断目标目录是否存在如果不存在则新建之
                if (!Directory.Exists(aimPath))
                {
                    Directory.CreateDirectory(aimPath);
                }
                // 得到源目录的文件列表，该里面是包含文件以及目录路径的一个数组
                string[] fileList = Directory.GetFileSystemEntries(srcPath);
                // 遍历所有的文件和目录
                foreach (string file in fileList)
                {
                    // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                    if (Directory.Exists(file))
                    {
                        CopyDir(file, aimPath + Path.GetFileName(file));
                    }
                    // 否则直接Copy文件
                    else
                    {
                        File.Copy(file, aimPath + Path.GetFileName(file), true);
                    }
                }
            }
            catch
            {
                return false;
            }
            Directory.Delete(srcPath, true);//删除源目录
            return true;
        }


        /// <summary>
        /// 文件拷贝 （附件转存）
        /// </summary>
        /// <param name="strid">移动的id</param>
        /// <param name="npath">移动到得路径</param>
        /// <returns></returns>
        public static bool MapPathCopy(string strid, string filename, string npath)
        {
            bool isSuc = false;
            try
            {
                Model.DiskGX d = disk.GetModel(conn, Convert.ToInt64(npath));
                if (d != null)
                {
                    string newpath = disk.GetParentPath(conn, npath, "");
                    newpath = Public_foldGX.GetPath(newpath, filename, d.DiskTypeID.ToString());
                    if (File.Exists(strid))
                    {
                        File.Copy(strid, newpath, true);
                        isSuc = true;
                    }
                }
            }
            catch
            {
                return false;
            }
            return isSuc;
        }


        /// <summary>
        /// 判断转存路径是否已存在同名文件
        /// </summary>
        public static bool IsExistName(string filename, string npath)
        {
            bool isSuc = false;
            try
            {
                Model.DiskGX d = disk.GetModel(conn, Convert.ToInt64(npath));
                if (d != null)
                {
                    string newpath = "";
                    newpath = disk.GetParentPath(conn, npath, "");
                    newpath = Public_foldGX.GetPath(newpath, filename, d.DiskTypeID.ToString());
                    if (File.Exists(newpath))
                    {
                        isSuc = true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch
            {
                return false;
            }
            return isSuc;
        }


        /// <summary>
        /// 判断文件或文件夹是否存在
        /// </summary>
        /// <param name="strid">移动的id</param>
        /// <param name="npath">移动到得路径</param>
        /// <returns></returns>
        public static bool PathIsExist(string strid, string npath)
        {
            bool isExist = false;
            try
            {
                List<AnyOffice.Model.DiskGX> files = disk.GetModelList(conn, " DiskID in(" + strid + ")");
                foreach (AnyOffice.Model.DiskGX f in files)
                {
                    string oldpath = "";
                    string newpath = "";
                    oldpath = disk.GetParentPath(conn, f.DiskID.ToString(), "");
                    newpath = disk.GetParentPath(conn, npath, "");
                    if (f.FileTypeID == 1)
                    {
                        oldpath = Public_foldGX.GetPath(oldpath, "", f.DiskTypeID.ToString());
                        newpath = Public_foldGX.GetPath(newpath, f.Name, f.DiskTypeID.ToString());
                        if (Directory.Exists(newpath))
                        {
                            isExist = true;
                            break;
                        }
                    }
                    else
                    {
                        oldpath = Public_foldGX.GetPath(oldpath, "", f.DiskTypeID.ToString());
                        newpath = Public_foldGX.GetPath(newpath, f.Name, f.DiskTypeID.ToString());
                        FileInfo fi = new FileInfo(newpath);
                        if (fi.Exists)
                        {
                            isExist = true;
                            break;
                        }
                    }
                }
            }
            catch
            {
                return false;
            }
            return isExist;
        }


        /// <summary>
        /// 物理删除
        /// </summary>
        /// <param name="strid">要删除的id</param>
        public static bool MapPathDel(string strid)
        {
            bool isExist = false;
            try
            {
                List<AnyOffice.Model.DiskGX> files = disk.GetModelList(conn, " DiskID in(" + strid + ")");
                foreach (AnyOffice.Model.DiskGX f in files)
                {
                    Model.DiskTypeGX dt = dbll.GetModel(conn, Convert.ToInt32(f.DiskTypeID));
                    string path = disk.GetParentPath(conn, f.DiskID.ToString(), "");
                    string filepath = dt.BasePath + "\\" + path;
                    if (f.FileTypeID == 1)
                    {
                        if (Directory.Exists(filepath))
                        {
                            Directory.Delete(filepath, true);
                            isExist = true;
                        }
                        else { isExist = false; }
                    }
                    else
                    {
                        FileInfo fi = new FileInfo(filepath);
                        if (fi.Exists)
                        {
                            fi.Delete();
                            isExist = true;
                        }
                        else { isExist = false; }
                    }
                }

            }
            catch
            {
                return false;
            }
            return isExist;
        }


        /// <summary>
        /// 对输入框的特殊字串进行过滤，防止SQL注入
        /// </summary>
        /// <param name="strFromText">要被过滤的字符串</param>
        /// <returns>过滤后的字符串</returns>
        public static string SqlInsertEncode(string strFromText)
        {
            if (!System.String.IsNullOrEmpty(strFromText) && strFromText != "")
            {
                strFromText = strFromText.Replace(";", "");
                strFromText = strFromText.Replace("!", "");
                strFromText = strFromText.Replace("@", "");
                strFromText = strFromText.Replace("$", "");
                strFromText = strFromText.Replace("*", "");
                strFromText = strFromText.Replace("(", "");
                strFromText = strFromText.Replace(")", "");
                strFromText = strFromText.Replace("-", "");
                strFromText = strFromText.Replace("—", "");
                strFromText = strFromText.Replace("+", "");
                strFromText = strFromText.Replace("=", "");
                strFromText = strFromText.Replace("|", "");
                strFromText = strFromText.Replace("\\", "");
                strFromText = strFromText.Replace("/", "");
                strFromText = strFromText.Replace("《", "");
                strFromText = strFromText.Replace("》", "");
                strFromText = strFromText.Replace(":", "");
                strFromText = strFromText.Replace("\"", "");
                strFromText = strFromText.Replace("'", "");
                strFromText = strFromText.Replace("<", "");
                strFromText = strFromText.Replace(" ", "");
                strFromText = strFromText.Replace(">", "");
                strFromText = strFromText.Replace(" ", "");
                strFromText = strFromText.Replace("%", "");
                strFromText = strFromText.Replace("#", "");
                strFromText = strFromText.Replace("~", "");
                strFromText = strFromText.Replace("&", "");
                strFromText = strFromText.Replace("，", "");
                strFromText = strFromText.Replace(",", "");
                strFromText = strFromText.Replace("^", "");
                strFromText = strFromText.Replace("_", "");
                strFromText = strFromText.Replace("：", "");
                strFromText = strFromText.Replace("。", "");
            }
            return strFromText;
        }
    }
}